﻿namespace ApiTemplate.WebApi
{
    /// <summary>
    /// 执行定时任务
    /// </summary>
    public class HttpJob : IJob
    {
        readonly ISchedulerTaskDAL _schedulerTaskDAL;
        readonly ISchedulerTaskLogDAL _schedulerTaskLogDAL;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="schedulerTaskDAL"></param>
        /// <param name="schedulerTaskLogDAL"></param>
        public HttpJob(ISchedulerTaskDAL schedulerTaskDAL, ISchedulerTaskLogDAL schedulerTaskLogDAL)
        {
            _schedulerTaskDAL = schedulerTaskDAL;
            _schedulerTaskLogDAL = schedulerTaskLogDAL;
        }

        /// <summary>
        /// 要执行方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            AddSchedulerTaskInput input = context.JobDetail.JobDataMap["input"] as AddSchedulerTaskInput;
            string taskId = context.JobDetail.JobDataMap["taskId"].ToString();
            string result;
            bool isSuccess;
            if (input.RequsetType == 0)//get
            {
                var exResult = await HttpHelper.GetAsync(input.Url);
                result = exResult.Item1;
                isSuccess = exResult.Item2;
            }
            else//post
            {
                var exResult = await HttpHelper.PostAsync(input.Url, input.Parameter);
                result = exResult.Item1;
                isSuccess = exResult.Item2;
            }
            var task = await _schedulerTaskDAL.GetSchedulerTaskOutputAsync(taskId);
            await _schedulerTaskDAL.UpdateSchedulerTaskAsync(new UpdateSchedulerTaskInput
            {
                CronStr = task.CronStr,
                Url = task.Url,
                Id = task.Id,
                Parameter = task.Parameter,
                RequsetType = task.RequsetType,
                TaskName = task.TaskName,
                LastExecTime = DateTime.Now
            });

            await _schedulerTaskLogDAL.AddSchedulerTaskLogAsync(new Entity.DataTable.SchedulerTaskLog
            {
                Result = result,
                TaskId = taskId,
                TaskName = input.TaskName,
                IsSuccess = isSuccess
            });
        }
    }
}
